﻿using Adp;
using Adp.Common;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using Yqd.Enm;
using Yqd.Models;

namespace Yqd.Core
{
    public class YqdUser
    {
        public string Avatar { get; set; }
        public string Name { get; set; }
        public int AccountId { get; set; }
        public string UnitCode { get; set; }
        public string UnitName { get; set; }
        public string EmployeeCode { get; set; }
        public string OrganizationCode { get; set; }
        public List<角色类型> Role { get; set; }
        public List<权限清单> Permit { get; set; }
        public int Dev { get; set; }
    }
    public class WxUser
    {
        public static YqdUser LogonInfo
        {
            get
            {
                var debugger = Form.GetBool("DeBugger", false);
                var Yu = new YqdUser();
                if (debugger)
                {
                    var ctx = Fn.GetService<YqdContext>();
                    var U = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == "GE_a6dabcc3edce4ebea9775dfa26ed99ed" && it.Status == 用户状态.使用中);
                    if (U != null)
                    {
                        var unit = ctx.Yqd_Unit.FirstOrDefault(it => it.OrganizationCode == U.UnitCode);
                        string UnitCode = "", UnitName = "";
                        if (unit != null)
                        {
                            UnitCode = unit.UnitCode;
                            UnitName = unit.Name;
                        }
                        Yu.EmployeeCode = U.EmployeeCode;
                        Yu.Name = U.Name;
                        Yu.AccountId = U.AccountId;
                        Yu.OrganizationCode = U.UnitCode;
                        Yu.UnitCode = UnitCode;
                        Yu.UnitName = UnitName;
                        Yu.Role = new List<角色类型>();
                        if (!string.IsNullOrWhiteSpace(U.Roles))
                        {
                            Yu.Role = U.Roles.Split(",").Select(it => (角色类型)int.Parse(it)).ToList();
                        }
                        Yu.Permit = new List<权限清单>();
                        if (!string.IsNullOrWhiteSpace(U.PermitItem))
                        {
                            Yu.Permit = U.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it)).ToList();
                        }
                        Yu.Avatar = U.Avatar;
                    }
                    return Yu;
                }
                var Employee = Cookie.Get("YqdEmployee");
                if (Employee.HasValue())
                {
                    Employee = Fn.DecryptDES(Employee);
                    return JsonConvert.DeserializeObject<YqdUser>(Employee);
                }
                return null;
            }
            set { }
        }

        public static string RedirectUrl
        {
            get
            {
                var url = "";
                var l = LogonInfo;
                if (l == null) return url;
                switch ((设备平台)l.Dev)
                {
                    case 设备平台.手机端:
                        if (l.Role.Any(it => it == 角色类型.管理员))
                        {
                            url = "/zld#/phone/index";
                        }
                        else if (l.Role.Any(it => it == 角色类型.市领导 || it == 角色类型.领导秘书))
                        {
                            url = "/zld#/phoneDing/dingIndex";
                        }
                        else if (l.Role.Any(it => it == 角色类型.督查人员 || it == 角色类型.督查管理员 || it == 角色类型.督查员))
                        {
                            url = "/dcd#/phone/index";
                        }
                        break;
                    default:
                        if (l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.市领导 || it == 角色类型.领导秘书))
                        {
                            url = "/zld";
                        }
                        else if (l.Role.Any(it => it == 角色类型.部门管理员 || it == 角色类型.部门流转员))
                        {
                            url = "/gzd";
                        }
                        else if (l.Role.Any(it => it == 角色类型.督查人员 || it == 角色类型.督查管理员 || it == 角色类型.督查员))
                        {
                            url = "/dcd";
                        }
                        break;
                }
                return url;
            }
        }

        public static List<dynamic> Platform
        {
            get
            {
                var platform = new List<object>();
                var l = LogonInfo;
                if (l == null) return platform;
                if (l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.市领导 || it == 角色类型.领导秘书))
                {
                    platform.Add(new { Text = "治理端", Url = "/zld", Value = 1 });
                }
                if (l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.部门管理员 || it == 角色类型.部门流转员))
                {
                    platform.Add(new { Text = "工作端", Url = "/gzd", Value = 2 });
                }
                if (l.Role.Any(it => it == 角色类型.管理员 || it == 角色类型.督查人员 || it == 角色类型.督查管理员 || it == 角色类型.督查员))
                {
                    platform.Add(new { Text = "督查端", Url = "/dcd", Value = 3 });
                }
                return platform;
            }
        }

        public static void LoginOut()
        {
            Cookie.Remove("YqdEmployee");
            LogonInfo = null;
        }
        public static void LoginMini(YqdUser user)
        {
            var js = JsonConvert.SerializeObject(user);
            Cookie.Set("YqdEmployee", Fn.EncryptDES(js), new CookieOptions
            {
                Expires = DateTime.Now.AddDays(30)
            });
        }

        public static int AddUser(string[] codes, int role, int PermitItem =0)
        {
            var ctx = Fn.GetService<YqdContext>();
            var ddService = Fn.GetService<DdService>();
            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            var l = LogonInfo;
            foreach (var code in codes)
            {
                if (ctx.Yqd_User.Any(it => it.EmployeeCode == code)) continue;
                var info = ddService.GetEmployeeInfo(code, config.TenantId);
                if (info == null) continue;
                var empJobLevelCode = info["empJobLevelCode"]?.ToString() ?? "";
                var empBudgetedPostCode = info["empBudgetedPostCode"]?.ToString() ?? "";
                var gender = info["empGender"]?.ToString()??"";
                var emp = new Yqd_User
                {
                    AccountId = 0,
                    Openid = "",
                    Roles = role.ToString(),
                    PermitItem = PermitItem.ToString(),
                    EmployeeCode = code,
                    Name = info["employeeName"]?.ToString() ?? "",
                    Avatar = info["govEmpAvatar"]?.ToString() ?? "",
                    Gender = gender != "" ? gender.ToInt() : 0,
                    OrganizationCode = l.OrganizationCode,
                    OrganizationName = l.UnitName,
                    UnitCode = l.OrganizationCode,
                    UnitName = l.UnitName,
                    empJobLevelCode = empJobLevelCode,
                    empBudgetedPostCode = empBudgetedPostCode,
                    empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode),
                    empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode),
                    Status = 用户状态.使用中,
                    Instime = DateTime.Now
                };
                var AccountId = ddService.listEmployeeAccountIds(emp.EmployeeCode, config.TenantId);
                if (AccountId?["accountId"] != null)
                {
                    emp.AccountId = AccountId["accountId"].ToString().ToInt();
                }
                ctx.Yqd_User.Add(emp);
            }
            return ctx.SaveChanges();
        }
    }
}